const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const redisClient = require('./utils/redisClient');
const redisStore = require('connect-redis')(session);

const index = require('./routes/index');
const users = require('./routes/users');
const foods = require('./routes/food');

const {secret} = require('./config');
const jwt = require('express-jwt');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    store: new redisStore({
        host:'localhost',
        port:'6379'
    }),
    secret,
    resave:false,
    saveUninitialized: true
}));
app.use(require('./middleware/message'));
app.use(jwt({
    secret,
    credentialsRequired: false,
    getToken: function fromHeaderOrQuerystringOrCookies(req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        } else if (req.cookies && req.cookies.token) {
            return req.cookies.token;
        }
        return null;
    }
}));

app.use('/', index);
app.use('/users', users);
app.use('/foods',foods);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // handler unauthorizedError, do not display a error
    if(err.name === 'UnauthorizedError'){
        res.clearCookie('token');
        res.redirect('/');
    }

    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error', {home: '/'});
});

module.exports = app;
